package sqlib;

import java.util.ArrayList;
import java.util.List;

public class SQLCreateTable extends SQLCommand {
	
	private static class Column { 
		private final String name;
		private final String type;
		private boolean primaryKey;
		
		public Column(String name, String type) {
			this.name = name;
			this.type = type;
			this.primaryKey = false;
		}
		
	}
	
	private String name;
	private List<Column> columns;
	
	public SQLCreateTable(String name) {
		this.name = name;
		columns = new ArrayList<SQLCreateTable.Column>();
	}
	
	public SQLCreateTable column(String name, String type) {
		columns.add(new Column(name, type));
		return this;
	}
	
	public SQLCreateTable asPrimaryKey() {
		if(columns.isEmpty())
			throw new IllegalStateException("no columns");
		
		columns.get(columns.size()-1).primaryKey = true;
		return this;
	}
	
	@Override
	public String getSQL() {
		String sql = "CREATE TABLE " + name + "(";
		
		for(int i = 0; i < columns.size(); i++) {
			if(i != 0)
				sql += ", ";
			Column c = columns.get(i);
			sql +=  c.name + " " + c.type;
			if(c.primaryKey)
				sql += " PRIMARY KEY";
			
		}
		sql += ");";
		return sql;
	}

	@Override
	public boolean isValid() {
		return !columns.isEmpty();
	}

}
